#!/usr/bin/env python
# coding:utf-8

from sql_rice.db import DBSET
from sql_rice.gui.widgets import TextWidget
from sql_rice.gui.window import FormWindow, GridWindow
from sql_rice.gui.action_area import SEARCH, UPDATE, DELETE, ADD

(TEXT, NUMBER, DATE, RANGE, ENUM) = list(range(1, 6))


WIDGET_TYPE = {'string': TEXT, 'int': NUMBER, 'enum': ENUM, 'TEXT': TEXT}

DEFAULT_FIELD = dict(name='', type='TEXT', length=0, not_null=False, \
                    default=None, pk=False)

WINDOW_TYPE = {'form':FormWindow,
               'grid':GridWindow}

WIDGETS = {DATE: TextWidget,
           TEXT: TextWidget,
           NUMBER: TextWidget,
           ENUM: TextWidget}


def create_window(ricer, connect_to):
    """create_window(ricer:dict, connect_to:dbconnection)->Window"""
    win = WINDOW_TYPE[ricer.get("display", "form")]()
    for widget_info in ricer['widgets']:
        widget = WIDGETS[widget_info['widget']](widget_info, win)
        win.add_widget(widget)
    sql = {'select': ricer['statement']['select']['sql'], 
            'insert': ricer['statement']['insert']['sql'],
            'delete': ricer['statement']['delete']['sql'],
            'update': ricer['statement']['update']['sql']}
    dbset = DBSET(sql, connect_to, 'sqlite3')
    win.actions.add(SEARCH, 'search',dbset.search)
    win.actions.add(UPDATE, 'update', dbset.update)
    win.actions.add(DELETE, 'delete', dbset.delete)
    win.actions.add(ADD, 'add', dbset.new)
    try:
        win.fill_grid(dbset.search({}))
    except AttributeError:
        pass
    return win


def create_widget_info(field, table, data_dict):
    """create_widget_info(field:str, table:str, data_dict:dict)->dict"""
    try:
        table = data_dict[table]
        field_obj = table[field]
    except KeyError:
        field_obj = DEFAULT_FIELD
    winfo = {'name': '', 'widget': '', 'rules': {}}
    winfo['name'] = field
    winfo['widget'] = WIDGET_TYPE.get(field_obj['type'], TEXT)
    if field_obj['length'] > 0:
        winfo['rules']['maxLength'] = {'length': field_obj['length']}
    if field_obj['default']:
        winfo['rules']['default'] = {'value': field_obj['default']}
    if field_obj['pk']:
        winfo['rules']['readOnly'] = {}
    if field_obj['not_null']:
        winfo['rules']['notEmpty'] = {}
    return winfo
